<?php

namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page; 

class SupplierController extends BaseController {
	function _initialize() {
		parent::_initialize ();
	}

	public function index() {
		$msg=M("wx_supplier");

		$keyword=I('keyword');
		
        $where="1=1"; 
        
		if($keyword)
		{ 
		   $where.=" and b.nickname  like '%".$keyword."%' or a.companyname like '%".$keyword."%' or a.abncode like '%".$keyword."%'  or a.linkname like '%".$keyword."%'";
		} 
		
		$where= str_replace("1=1 and", "", $where);
		$where= str_replace("1=1", "", $where);
		
	   // $count =$msg->alias("a")->join(" inner join ".$this->dbprefix."wx_openuser c on a.openid=c.openid")->join(" left join ".$this->dbprefix."users b on a.user_id=b.user_id")->join(" left join ".$this->dbprefix."admin_user d on a.operationuser=d.user_id")->where($where)->count(); // 查询满足要求的总记录数
        $count =$msg->alias("a")->join(" left join ".$this->dbprefix."users b on a.user_id=b.user_id")->join(" left join ".$this->dbprefix."admin_user d on a.operationuser=d.user_id")->where($where)->count(); // 查询满足要求的总记录数

		$Page = new Page ($count, 12 ); // 实例化分页类 传入总记录数和每页显示的记录数
		$Page -> setConfig('header', '条记录');
		$Page -> setConfig('theme', '<li><a>%totalRow% %header%</a></li> <li>%upPage%</li> <li>%downPage%</li> <li>%first%</li>  <li>%prePage%</li>  <li>%linkPage%</li>  <li>%nextPage%</li> <li>%end%</li> ');//(对thinkphp自带分页的格式进行自定义)
		$show = $Page->show (); // 分页显示输出

		//$ret=$msg->alias("a")->field("a.*,c.nickname,c.sex,c.headimgurl,c.country,c.province,c.city,b.user_name as username,d.user_name as adminname")->join(" inner join ".$this->dbprefix."wx_openuser c on a.openid=c.openid")->join(" left join ".$this->dbprefix."users b on a.user_id=b.user_id")->join(" left join ".$this->dbprefix."admin_user d on a.operationuser=d.user_id")->where($where)->limit( $Page->firstRow . ',' . $Page->listRows )->order("a.createtime desc")->select(); 
        $ret=$msg->alias("a")->field("a.*,b.user_name as username,d.user_name as adminname")->join(" left join ".$this->dbprefix."users b on a.user_id=b.user_id")->join(" left join ".$this->dbprefix."admin_user d on a.operationuser=d.user_id")->where($where)->limit( $Page->firstRow . ',' . $Page->listRows )->order("a.createtime desc")->select(); 
        
        foreach ($ret as $key => $value) {
        	if(!empty($value['openid'])){
        		$wx_list = D('wx_openuser')->field('nickname,sex,headimgurl,country,province,city')->where('openid="'.$value['openid'].'"')->find();
        		if(!empty($wx_list)){
        		$value['nickname'] = $wx_list['nickname'];
        		$value['sex'] = $wx_list['sex'];
        		$value['headimgurl'] = $wx_list['headimgurl'];
        		$value['country'] = $wx_list['country'];
        		$value['province'] = $wx_list['province'];
        		$value['city'] = $wx_list['city'];
        		$ret[$key] = $value;
        		}
        	}
        }

        //0待审核，1有效，2资料不合格，3删除标识
		$aryactive=array(0=>'待审核',1=>'有效',2=>'资料不合格',3=>'删除标识');
		$this->assign ( "active", $aryactive );
		
		$this->assign ( "list", $ret );
		$this->assign ( "page", $show ); // 赋值分页输出 
		$this->display ();
	}
	
	//有个传递特价主题编号，一个是没有传主题编号
	public function add()
	{
		$id=I("spid");		
		$id= isset($id)?$id:'';
		$id =empty($id)?'':$id;  
		 
		if($id){
		  $ret=M("wx_supplier")->alias("a")->field("a.*,c.openid,c.nickname,c.sex,c.headimgurl,c.country,c.province,c.city,b.user_name as username")->join(" inner join ".$this->dbprefix."wx_openuser c on a.openid=c.openid")->join(" left join ".$this->dbprefix."users b on a.user_id=b.user_id")->where("a.sp_id='$id'")->find();
		}
		
		$this->assign ("entity",$ret); 
		$this->display ();
	}
 
   
	public function addsupplier() {	
		
		$spid=I("sp_id");  
		$data=$_POST; 
		
		if(empty($data['openid']) ||empty($data['username']) || empty($data['companyname']) || empty($data['abncode'])|| empty($data['linkname'])|| empty($data['moblie'])|| empty($data['address']) ){
			$this->error("请填写完整的信息");
		} 
		
		$db=M("wx_supplier");
		$userdbo=M("users"); 
		 
		
		$retopen= M("wx_openuser")->where("openid='".$data["openid"]."'")->find();
		if(!$retopen){
			$this->error("微信用户不存在");
		}
		
		$postdata=array();
		$postdata['sp_id']=$data['sp_id'];
		$postdata['user_id']=0;
		$postdata['openid']=$data['openid'];
		$postdata['companyname']=$data['companyname'];
		$postdata['abncode']=$data['abncode'];
		$postdata['address']=$data['address'];
		$postdata['linkname']=$data['linkname']; 
		$postdata['moblie']=$data['moblie'];
		$postdata['isactive']=$data['isactive'];
		$postdata['createtime']=date("Y-m-d H:i:s");
		$postdata['operationuser']=UID; 
		
		$db->startTrans();
		
		//新增 对数据判断
		if(empty($spid)){
			if(empty($data['openid']) || empty($data['username'])|| empty($data['password']) ){
				$this->error("请选择微信用户，填写用户账号，密码");
			} 
			
			$userlist=$userdbo->where("user_name='".$data['username']."'")->select();
			if($userlist){
				$this->error("用户账号已经存在！");
			}
			
			//增加用户
			$ec_salt = $ec_salt=rand(1,9999);
			$userdata=array('user_name'=>$data['username'],'password'=>md5(md5($data['password']).$ec_salt),'ec_salt'=>strval($ec_salt),'moblie_phone'=>$data['moblie'],'sex'=>($retopen['sex']==1?1:0));
			$retuser=$userdbo->add($userdata);
			
			if(!$retuser){
				$db->rollback();
				$this->error("保存用户账号失败");
			}  
			
			$postdata['user_id']=$retuser;
			
			//绑定用户与微信openid
			$userbin=M("wx_binduser")->where("openid='".$data["openid"]."' and user_id='".$retuser."'")->find();
			if(!$userbin){ 
			  $bindata=array('wx_id'=>getGuid(),'user_id'=>$retuser,'openid'=>$data["openid"],'bindtype'=>'user','createtime'=>date("Y-m-d H:is"));
			  $retbin=M("wx_binduser")->add($bindata);
			  if(!$retbin){
			  	$db->rollback();
			  	$this->error("绑定数据失败"); 
			  }
			}
			
			//新增供应商记录
			$retext= $db->where("companyname='".$data['companyname']."' or (companyname='".$data['companyname']."' and 'moblie'='".$data['moblie']."')")->select();
			if($retext){
				$db->rollback();
				$this->error("供应商已经存在"); 
			}
			
			$postdata['sp_id']=getGuid();
			$retadd=$db->add($postdata);
			if($retadd){
				$db->commit();
				$this->success("添加供应商信息成功",U("Supplier/index"));
				
			}
			else{
				$db->rollback();
				$this->error("添加供应商信息失败");
				
			}
			
		}
		else { //修改数据   
			$retsup=$db->where("sp_id='".$spid."'")->find();
			if(!$retsup){
				$this->error("供应商信息不存在！");
			} 
			
			$userid=$retsup['user_id'];
			
			if($retsup['user_id']==0){
			   $user=$userdbo->where("user_name='".$data['username']."' ")->find();
			   if(!$user){
			   	  $this->error("用户账号不存在！");
			   }
			   $userid=$user['user_id'];
			} 
			
			$postdata['user_id']=$userid;
			
			$rs=$db->save($postdata); 
			if($rs){
				$db->commit();
				$this->success("修改供应商信息成功",U("Supplier/index"));
				
			}
			else{
				$db->rollback();
				$this->error("修改供应商信息失败");
				
			}
		} 
		 
		
	}

	public function delsupplier(){
		$id=I("id");
		if(empty($id)){
			$this->error("传递参数错误!");
		} 
		$where="FIND_IN_SET(sp_id,'$id')";
		$result = M("wx_supplier")->where($where)->delete();
		if ($result) {
			$this->success("删除成功!");
		}
		else{
			$this->error ( "删除失败！" );
		}
	}
	
	 //设置状态
	 public function setsupplier(){
	 	$ret=array('staute'=>'error','msg'=>"设置状态失败");
	 	$id=$_GET["id"];
	 	$_actives=$_GET["actives"];
	 	if($id==""||$_actives==""){ 
	 		$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
	 	}
	 	$where=" FIND_IN_SET(sp_id,'$id')";
	 	$sql="update ".$this->dbprefix."wx_supplier set isactive='$_actives' , operationuser = ".UID." where ".$where;
	 	$result = M("wx_supplier")->execute($sql);
	 	if ($result) {
	 		$ret=array('staute'=>'success','msg'=>"设置状态成功");
	 	}
	 	$this->ajaxReturn ($ret);
	 }

	/*
	public function getbyid(){
		$result = M("wx_reply")->where(array("id"=>$_POST["id"]))->find();
		if ($result) {
			$this->ajaxReturn($result);
		}
	} 
	*/

}
?>
